<template>
  <view-box ref="viewBox" body-padding-bottom="5px">
    <div id="box">
      <p class="desc">请选择或者输入金额</p>
      <div class="flex-box">
        <span @click="amount=10">10</span>
        <span @click="amount=50">50</span>
        <span @click="amount=100">100</span>
        <span @click="amount=200">200</span>
        <span @click="amount=300">300</span>
        <span @click="amount=500">500</span>
      </div>
      <group>
        <x-input title="捐助金额：" type="number" v-model="amount" placeholder="请输入捐助的金额"></x-input>
        <x-textarea title="有话要说：" v-model="comment" placeholder="请说出你想说的话"></x-textarea>
      </group>
      <x-button type="primary" @click.native="generateOrder" :disabled="loading" :show-loading="loading">马上支付</x-button>
      <x-button @click.native="$router.push('/donation')">下次再来</x-button>
    </div>
  </view-box>
</template>
<script>
  import { ViewBox, XButton, Group, XInput, XTextarea } from 'vux'
  export default {
    data () {
      return {
        loading: false,
        amount: 100,
        comment: ''
      }
    },
    components: {
      ViewBox,
      XButton,
      Group,
      XInput,
      XTextarea
    },
    methods: {
      generateOrder () {
        // check product data
        if (!this.amount) {
          this.$vux.toast.show('请输入众筹金额')
          return false
        }
        this.loading = true
        this.$http.post('/donations', {amount: this.amount, comments: this.comment}).then((response) => {
          // 支付
          this._pay(response.data)
        }).catch((error) => {
          this.loading = false
          console.log(error)
        })
      },
      _pay (json) {
        let callpay = () => {
          if (typeof WeixinJSBridge === 'undefined') {
            if (document.addEventListener) {
              document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false)
            } else if (document.attachEvent) {
              document.attachEvent('WeixinJSBridgeReady', onBridgeReady)
              document.attachEvent('onWeixinJSBridgeReady', onBridgeReady)
            }
          } else {
            onBridgeReady()
          }
        }
        let onBridgeReady = () => {
          WeixinJSBridge.invoke('getBrandWCPayRequest', json, (res) => {
            if (res.err_msg === 'get_brand_wcpay_request:ok') {
              this.$router.replace('/donation')
            } else {
              this.$router.replace('/donation')
            }
          })
        }
        callpay()
      }
    }
  }
</script>
<style scoped lang="less">
  #box {
    padding: 30px;
  }
  .desc {
    color: #000;
    text-align: center;
    font-weight: bold;
    margin-bottom: 20px;
  }
  .flex-box {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
    span {
      display: block;
      width: 48%;
      background: #ff6766;
      text-align: center;
      margin-bottom: 15px;
      padding: 8px 0;
      border-radius: 5px;
      color: #fff;
    }
  }
</style>